<?php

if(!defined('_COMMON_')) {
define('_COMMON_', 1);

include  _ITSTOCK_LIB_DIR_.'search.inc.php';

/**
 * Starts the php session.<br>
 * A new one is created if the previous one already expired.
 */
function itstock_session_start() {
  session_set_cookie_params( _ITSTOCK_SESSION_TIMEOUT_, _ITSTOCK_SERVER_DIR_);
  session_name('itss');
  session_start();
  setcookie(session_name(), session_id(), time() +  _ITSTOCK_SESSION_TIMEOUT_);
}

/**
 * Ends the session.
 */
function itstock_logout() {
  session_unset();
  session_destroy();
}

/**
 * Starts the session.
 * 
 * @return boolean <b>true</b> on success.
 * <b>false</b> on failure.
 */
function itstock_login(&$auth_data, $user, $pass) {
  $user = trim($user);
  $pass = trim($pass);
  if($user === '' || $pass === '') {
    $_SESSION['error'] = 'Please Insert a Valid Username and Password.';
  } else {
    $ds = ldap_connect($GLOBALS['ADS_CONFIG']['server']);
    if ($ds) {
      ldap_set_option($ds, LDAP_OPT_REFERRALS, 0);
      ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
      $ldapbind = @ldap_bind($ds, $GLOBALS['ADS_CONFIG']['usr_prefix'].$user, $pass);
      if ($ldapbind) {
        $filter = sprintf($GLOBALS['ADS_CONFIG']['filter'], $user);
        $sr = ldap_search($ds, $GLOBALS['ADS_CONFIG']['dn'], $filter, $GLOBALS['ADS_CONFIG']['justthese']);
        if($sr) {
          $auth_data['ldap'] = ldap_get_entries($ds, $sr);
          if($auth_data['ldap']['count'] > 0) {
            $auth_data['countdown'] = 0;
            $auth_data['ads_u'] = $user;
            $auth_data['ads_p'] = $pass;
            ldap_close($ds);
            return $auth_data['login'] = true;
          } else {
            $_SESSION['error'] = 'Access Denied to User: '.$user;
          }
        } else {
          $_SESSION['error'] = 'Error on search LDAP Server';
        }
      } else {
        $_SESSION['error'] = 'Username or Password Invalid.';
      }
      ldap_close($ds);
    } else {
      $_SESSION['error'] = 'Could not connect to LDAP Server.';
    }
  }
  return $auth_data['login'] = false;
}

/**
 * Valid session.
 * 
 * @return boolean <b>true</b> on success.
 * <b>false</b> on failure.
 */
function itstock_valid_login(&$auth_data) {
  if (isset($auth_data['login']) && $auth_data['login'] && isset($auth_data['countdown'])) {
    if ($auth_data['countdown'] >= _ITSTOCK_ADS_COUNT_) {
      return $auth_data['login'] = itstock_login($auth_data, $auth_data['ads_u'], $auth_data['ads_p']);
    }
    $auth_data['countdown']++;
    return true;
  }
  return false;
}

function itstock_structure(&$data, $type) {
  if (file_exists( _ITSTOCK_STRUCT_DIR_ . '/' . $type . '.inc.php')) {
    include  _ITSTOCK_STRUCT_DIR_ . '/' . $type . '.inc.php';
    return true;
  }
  return false;
}

function itstock_get(&$data, $field, $i = 0) {
  if (array_key_exists('data', $data) && array_key_exists($field, $data['data'][$i])) {
    return $data['data'][$i][$field];
  }
  return null;
}

function itstock_ldap_get(&$auth_data, $attr, $i = 0) {
  return isset($auth_data['ldap'][0][$attr][$i])? $auth_data['ldap'][0][$attr][$i]: null;
}

function itstock_array_value(&$array, $idx){
  return isset($array[$idx])? $array[$idx] : null;
}

function itstock_encode($id) {
  if(is_null($id)) return null;
  $rnd = openssl_random_pseudo_bytes(4);
  return base_convert($id . bin2hex($rnd), 16, 10);
}

function itstock_decode($id) {
  if (!is_numeric($id))
    return 0;
  $str = sprintf("%024s", base_convert($id, 10, 16));
  return sprintf("%d", substr($str, 0, 16));
}

function itstock_pass($pass) {
  return md5($pass);
}

}
?>
